package org.sction.manager;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.sction.util.FileUtils;


/**
 * @author 作者 : Administrator
 * @version 创建时间：2013年8月21日 下午5:41:49
 * 
 *          类说明
 */
public class SystemHelper {
	private static final Logger logger = Logger.getLogger(SystemHelper.class);

	// 操作系统名称
	public static String OS_NAME = System.getProperty("os.name");
	public static String OS_VERSION = System.getProperty("os.version");
	// 行分页符
	public static String OS_LINE_SEPARATOR = System
			.getProperty("line.separator");
	// 文件分隔符号
	public static String OS_FILE_SEPARATOR = System
			.getProperty("file.separator");

	public static String OS_PATH_SEPARATOR = System
			.getProperty("path.separator");

	public static String JAVA_RUNTIME_NAME = System
			.getProperty("java.runtime.name");

	public static String JAVA_RUNTIME_VERSION = System
			.getProperty("java.runtime.version");

	public static String JAVA_IO_TMPDIR = System.getProperty("java.io.tmpdir");
	public static String JAVA_VERSION = System.getProperty("java.version");

	public static String USER_TIMEZONE = System.getProperty("user.timezone");

	public static String USER_DIR = System.getProperty("user.dir");

	public static String USER_LANGUAGE = System.getProperty("user.language");

	public static String FILE_ENCODING = System.getProperty("file.encoding");

	public static String USER_NAME = System.getProperty("user.name");

	public static String JAVA_HOME = System.getProperty("java.home");

	/**
	 * 
	 * 根据系统的类型获取本服务器的ip地址
	 * 
	 * InetAddress inet = InetAddress.getLocalHost(); 但是上述代码在Linux下返回127.0.0.1。
	 * 主要是在linux下返回的是/etc/hosts中配置的localhost的ip地址，
	 * 而不是网卡的绑定地址。后来改用网卡的绑定地址，可以取到本机的ip地址：）：
	 * 
	 * @throws UnknownHostException
	 */
	public static InetAddress getSystemLocalIp() throws UnknownHostException {
		InetAddress inet = null;
		try {
			// 针对window系统
			if (OS_NAME.toLowerCase().startsWith("windows")) {
				inet = getWinLocalIp();
				// 针对linux系统
			} else if (OS_NAME.toLowerCase().startsWith("linux")) {
				inet = getUnixLocalIp();
			}
			if (null == inet) {
				inet = getWinLocalIp();
			}
		} catch (SocketException e) {
			logger.error("获取本机ip错误" + e.getMessage());
			throw new UnknownHostException("获取本机ip错误" + e.getMessage());
		}
		return inet;
	}

	/**
	 * 获取主机所有IP
	 * 
	 * @return
	 * @throws UnknownHostException
	 */
	public static InetAddress[] getSystemLocalIps() throws UnknownHostException {

		try {
			// 针对window系统
			if (OS_NAME.toLowerCase().startsWith("windows")) {
				return getWinLocalIps();
				// 针对linux系统
			} else if (OS_NAME.toLowerCase().startsWith("linux")) {
				return getUnixLocalIps();
			} else {
				return getWinLocalIps();
			}
		} catch (SocketException e) {
			logger.error("获取本机ip错误" + e.getMessage());
			throw new UnknownHostException("获取本机ip错误" + e.getMessage());
		}
	}

	/**
	 * 获取window 本地ip地址
	 * 
	 * @return
	 * @throws UnknownHostException
	 */
	private static InetAddress getWinLocalIp() throws UnknownHostException {
		return InetAddress.getLocalHost();
	}

	private static InetAddress[] getWinLocalIps() throws UnknownHostException {
		return InetAddress.getAllByName(InetAddress.getLocalHost()
				.getHostName());
	}

	private static String getHostName() throws UnknownHostException {
		return InetAddress.getLocalHost().getHostName();
	}

	/**
	 * 
	 * 可能多多个ip地址只获取一个ip地址 获取Linux 本地IP地址
	 * 
	 * @return
	 * @throws SocketException
	 */
	private static InetAddress getUnixLocalIp() throws SocketException {
		Enumeration<NetworkInterface> netInterfaces = NetworkInterface
				.getNetworkInterfaces();
		InetAddress ip = null;
		while (netInterfaces.hasMoreElements()) {
			NetworkInterface ni = (NetworkInterface) netInterfaces
					.nextElement();
			ip = (InetAddress) ni.getInetAddresses().nextElement();
			if (!ip.isSiteLocalAddress() && !ip.isLoopbackAddress()
					&& ip.getHostAddress().indexOf(":") == -1) {
				return ip;
			} else {
				ip = null;
			}
		}
		return null;
	}

	private static InetAddress[] getUnixLocalIps() throws SocketException {
		Enumeration<NetworkInterface> netInterfaces = NetworkInterface
				.getNetworkInterfaces();
		List<InetAddress> ips = new ArrayList<InetAddress>();
		while (netInterfaces.hasMoreElements()) {
			NetworkInterface ni = (NetworkInterface) netInterfaces
					.nextElement();
			Enumeration<InetAddress> ias = ni.getInetAddresses();
			while (ias.hasMoreElements()) {
				ips.add(ias.nextElement());
			}
		}
		return (InetAddress[]) ips.toArray();
	}

	/**
	 * 
	 * 获取当前运行程序的内存信息
	 * 
	 * @return
	 */
	public static final String getRAMinfo() {
		Runtime rt = Runtime.getRuntime();
		return "RAM: " + rt.totalMemory() + " bytes total, " + rt.freeMemory()
				+ " bytes free. maxMemory: " + rt.maxMemory() + " bytes max.";
	}

	public static final String getRAMinfox() {
		Runtime rt = Runtime.getRuntime();
		return "RAM: " + FileUtils.getFileSize(rt.totalMemory()) + " TOTAL, "
				+ FileUtils.getFileSize(rt.freeMemory()) + " FREE, "
				+ FileUtils.getFileSize(rt.maxMemory()) + " MAX.";
	}

	public static void main(String[] args) throws UnknownHostException {
		Enumeration<Object> keys = System.getProperties().keys();
		while (keys.hasMoreElements()) {
			String key = (String) keys.nextElement();
			System.out.println(key + ":" + System.getProperty(key));
		}
		System.out.println(getRAMinfo());
		System.out.println(getRAMinfox());
		InetAddress[] ias = getSystemLocalIps();
		for (int i = 0; i < ias.length; i++) {
			InetAddress inetAddress = ias[i];
			System.out.println(inetAddress.getHostAddress());
		}
	}
}
